#include "KmyNode.h"

KmyNode::KmyNode()
{
    parent = NULL;
    x = 0;
    y = 0;
    z = 0;
    drawtask = NULL;
}

KmyNode::~KmyNode(){

}

void KmyNode::finalize(){
    ST_VectorNode *p = child_list.getHead();
    while (p!=NULL){
        KmyNode* node= (KmyNode*)(p->value);
        node->finalize();
        delete node;
        p = p->next;
    }
    child_list.clear();
    if (parent!=NULL){
        parent->removeChild(this);
    }
}

int KmyNode::getNodeType(){
    return NODE_TYPE_BASE;
}

    /** id计数器从100000开始 */
int KmyNode::id_counter = 100000;

int KmyNode::createID(){
    id_counter++;
    return id_counter;
}

void KmyNode::addChild(KmyNode *child){
    if (child->id==0){
        child->id = KmyNode::createID();
    }

    if (child->parent!=NULL){
        return;
    }
    child_list.addValue((void*)child);
    child->parent = this;
}

void KmyNode::removeChild(KmyNode *child){
    if (child->parent!=this){
        return;
    }

    child_list.removeValue((void*)child);
    child->parent = NULL;
}

void KmyNode::logic(){
    ST_VectorNode *p = child_list.getHead();
    while (p!=NULL){
        KmyNode *node = (KmyNode*)(p->value);
        node->logic();
        p = p->next;
    }
}

void KmyNode::render(KmyICanvas *screen){
    ST_VectorNode *p = child_list.getHead();
    while (p!=NULL){
        KmyNode *node = (KmyNode*)(p->value);
//        if (node->isInScreen(screen)){
            node->render(screen);
//        }
        p = p->next;
    }
}

int KmyNode::getGlobalX(){
    if (parent!=NULL){
        return parent->getGlobalX()+x;
    }else{
        return x;
    }
}

int KmyNode::getGlobalY(){
    if (parent!=NULL){
        return parent->getGlobalY()+y;
    }else{
        return y;
    }
}

int KmyNode::getGlobalZ(){
    if (parent!=NULL){
        return parent->getGlobalZ()+z;
    }else{
        return z;
    }
}

//bool KmyNode::isInScreen(KmyICanvas* screen){
//    int gx = getGlobalX();
//    int gy = getGlobalY();
//    if (gx+max_range.x+max_range.w<0
//            ||gx+max_range.x>screen->WIDTH
//            ||gy+max_range.y+max_range.h<0
//            ||gy+max_range.y>screen->HEIGHT){
//        return false;
//    }
//    return true;
//}

int KmyNode::getX(){
    return x;
}

int KmyNode::getY(){
    return y;
}

int KmyNode::getZ(){
    return z;
}

void KmyNode::setX(int x){
    if (this->x!=x){
        is_updated = true;
        this->x = x;
    }
}

void KmyNode::setY(int y){
    if (this->y!=y){
        is_updated = true;
        this->y = y;
    }
}

void KmyNode::setZ(int z){
    if (this->z!=z){
        is_updated = true;
        this->z = z;
    }
}

void KmyNode::move(int dx, int dy, int dz){
    if (dx!=0 || dy!=0 || dz!=0){
        is_updated = true;
        x = x+dx;
        y = y+dy;
        z = z+dz;
    }
}
